package com.greenline.search.test.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: liulei
 * Date: 13-9-29
 * Time: 上午10:27
 * 文件操作的相关方法，包括文件读取和写入。
 */
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 从文件中读取内容，以每行为单位存到一个List当中，然后返回文件所有内容的List对象
     * @param filePath 要读取内容的文件路径
     * @param charset 文件的编码
     * @return
     */
    public static List<String> readFileAsString(String filePath, String charset){
        List<String> contentList = new ArrayList<String>();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset));
        } catch (FileNotFoundException e) {
            logger.error("File not found. The err message: {}", e.getMessage());
            return contentList;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null){
                contentList.add(line.trim());
            }
        } catch (IOException e) {
            logger.error("Read file encountered an error.The err message:{}",e.getMessage());
            return contentList;
        }

        return contentList;
    }

    public static void main(String[] args) {
        String classPath = FileUtils.class.getResource("/").getPath();
        String filePath = classPath+"dic/stopwords.txt";
        List<String> contentString = FileUtils.readFileAsString(filePath, "GBK");
        if(contentString.size() > 0 ){
            System.out.println(contentString.get(0));
        }else{
            System.out.println("Content string is empty!");
        }


    }
}
